package com.egzosn.service.pay.handler;

import com.egzosn.pay.common.api.PayService;
import com.egzosn.pay.common.bean.PayMessage;
import com.egzosn.pay.common.bean.PayOutMessage;
import com.egzosn.pay.common.exception.PayErrorException;
import org.springframework.stereotype.Component;

import java.math.BigDecimal;
import java.util.Map;

/**
 * 支付宝支付回调处理器
 * Created by egan on 2016/6/1.
 *
 */
@Component
public class AliPayMessageHandler extends BasePayMessageHandler {



    @Override
    public PayOutMessage handle(PayMessage payMessage, Map<String, Object> context, PayService payService) throws PayErrorException {

        Map<String, Object> message = payMessage.getPayMessage();
        //交易状态
        String trade_status = (String) message.get("trade_status");
       /* if (null == trade_status){
            trade_status = "TRADE_SUCCESS";
        }*/

        //交易完成
        if ("TRADE_SUCCESS".equals(trade_status) || "TRADE_FINISHED".equals(trade_status)) {
            BigDecimal payAmount = null;
            if (null != message.get("total_fee")){
                 payAmount = new BigDecimal((String) message.get("total_fee"));
            }else {
                payAmount = new BigDecimal((String) message.get("total_amount"));
            }

            //这里进行业务处理
            handle(payMessage.getOutTradeNo(), payAmount, message.toString(),  (Integer) payService.getPayConfigStorage().getAttach());
            return payService.successPayOutMessage(payMessage);

        }/* else if ("WAIT_BUYER_PAY".equals(trade_status) || "TRADE_CLOSED".equals(trade_status)) {

        }*/
        return payService.getPayOutMessage("fail", "失败");
    }
}
